import React, { useEffect, useImperativeHandle, useMemo } from 'react';
import { defaultFormatResult, useRequest } from '@/hooks';
import { getEmployeeOrgTree } from '@/pages/Organization/OrgFlow/services';
import { message, Spin, Table, Tooltip, TreeSelect } from 'antd';
import Icon from '@/components/IconPro';
import { array2Tree, filterTreeData, getTreeNodePath, mapTreeData } from '@/utils/tree';
import EmployeeTransfer from '@/pages/Organization/OrgFlow/Department/components/EmployeeTransfer';
import { cloneDeep, flatten } from 'lodash';
import { getOrganizationWithFullName } from '@/pages/EntryManage/services';
import useControllableValue from '@/hooks/useControllableValue';
import IconFont from '@/components/IconFont';
import styles from './index.less';

function filterTreeDisableItemChildren(tree, fn) {
    return tree.map(item => {
        const itemClone = { ...item };
        if (itemClone.children) {
            itemClone.children = filterTreeDisableItemChildren(itemClone.children, fn);
        }
        if (itemClone.disabled) {
            delete itemClone.children;
        }
        return itemClone;
    });
}

const EmployeeManage = React.forwardRef((props, ref) => {
    const { organizationCode } = props;
    const [value = [], onChange] = useControllableValue(props);

    // 获取服务端数据
    const { data: employeeAndOrgData, loading: employeeAndOrgLoading } = useRequest(
        () => getEmployeeOrgTree(organizationCode),
        {
            refreshDeps: [organizationCode],
            ready: organizationCode,
            ...defaultFormatResult
        }
    );
    // 获取面包屑机构路径
    const { data: baseOrganizationPath } = useRequest(() => getOrganizationWithFullName([organizationCode]), {
        ready: !!organizationCode,
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    // baseOrganizationPath[0].fullOrganizationName
                    // baseOrganizationPath[0].fullOrganizationPath
                    let path = data?.[0]?.fullOrganizationName;
                    path = path?.substr(0, path.lastIndexOf('/'));
                    return path;
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    // 机构树
    const [departmentOrganizationTree, allLeaves] = useMemo(() => {
        // 机构列表 / 员工列表
        const { departmentOrganizationDtoList = [], departmentEmployeeDtoList = [] } = employeeAndOrgData || {};
        const changedEmployeeIds = value.map(item => item.employeeCode);
        // 排除掉已选择过的数据
        const enableDepartmentEmployeeDtoList = departmentEmployeeDtoList.filter(
            item => !changedEmployeeIds.includes(item.employeeCode)
        );
        // 合并了机构列表和员工列表的数组
        const organizationTreeDataConcatEmployeeData = departmentOrganizationDtoList.map(item => ({
            ...item,
            id: item.organizationPath,
            pId: item.parentOrganizationPath,
            name: item.organizationName,
            disabled: item.auditStatus !== 2,
            // 把关联的员工合并到树节点中
            leaves: enableDepartmentEmployeeDtoList
                .filter(node => node.organizationCode === item.organizationCode)
                .map(leaf => ({
                    ...leaf,
                    id: leaf.employeeCode,
                    pId: item.organizationPath,
                    name: leaf.employeeName,
                    disabled: !!leaf.leaderPositionFlag
                }))
        }));
        // 转成树数据
        let tree = organizationTreeDataConcatEmployeeData ? array2Tree(organizationTreeDataConcatEmployeeData) : [];
        tree = filterTreeDisableItemChildren(tree);
        return [tree, flatten(organizationTreeDataConcatEmployeeData.map(item => item.leaves))];
    }, [value, employeeAndOrgData]);

    useEffect(() => {
        const scrollWrapper = document.querySelector('.ant-tabs-tabpane-active .tab-scroll-context');
        if (value?.length && scrollWrapper) {
            scrollWrapper.scrollTop = 10000;
        }
    }, [value]);

    // 新增员工变动数据
    const handleAddEmployeeData = values => {
        const valuesId = values.map(item => item.employeeCode);
        let changedEmployeeData = cloneDeep(value || []);
        // 去掉重复项 与 变更前和变更后数据一致的记录
        changedEmployeeData = changedEmployeeData.filter(item => !valuesId.includes(item.employeeCode));
        // 合并新数据
        changedEmployeeData = changedEmployeeData.concat(values.filter(item => item.fromOrgCode !== item.toOrgCode));
        onChange(changedEmployeeData);
    };

    // 新增员工变动数据
    const handleDeleteEmployeeData = employeeCode => {
        onChange(value.filter(item => item.employeeCode !== employeeCode));
    };

    // 更改员工数据
    const handleChangeEmployeeOrganization = (employeeCode, changeData) => {
        const changedItemIndex = value.findIndex(item => item.employeeCode === employeeCode);
        const targetItem = employeeAndOrgData?.departmentOrganizationDtoList.find(
            item => item.organizationCode === changeData
        );
        let changedEmployeeData = cloneDeep(value);
        if (changedItemIndex > -1) {
            const toOrgPathNodes = getTreeNodePath(departmentOrganizationTree, 'organizationCode', changeData);
            const toOrgPathCode = toOrgPathNodes?.map(item => item.organizationCode);
            const toOrgPathName = toOrgPathNodes?.map(item => item.organizationName);
            changedEmployeeData[changedItemIndex] = {
                ...changedEmployeeData[changedItemIndex],
                toOrgCode: targetItem.organizationCode,
                toOrgName: targetItem.organizationName,
                toOrgPathCode: toOrgPathCode.join('/'),
                toOrgPathName: toOrgPathName.join('/'),
                // toFullOrgPathCode: 'TODO',
                toFullOrgPathName: [baseOrganizationPath, ...toOrgPathName].join('/')
            };
            changedEmployeeData = changedEmployeeData.filter(item => item.fromOrgCode !== item.toOrgCode);
            onChange(changedEmployeeData);
        }
    };

    const columns = [
        {
            title: '员工',
            dataIndex: 'employeeName',
            render: (text, record) => (
                <div>
                    {text}
                    <span style={{ color: '#8C8C8C' }}> - {record.fromDutyName}</span>
                </div>
            )
        },
        {
            title: '变更前',
            dataIndex: 'fromOrgName',
            render: (text, record) => (
                <div>
                    {text}&nbsp;
                    <Tooltip title={record.fromFullOrgPathName} placement="top">
                        <IconFont
                            icon="iconlistfunction_moreinfos_icon_default"
                            className="autoVisibleIcon"
                            style={{ fontSize: 16, verticalAlign: -1 }}
                        />
                    </Tooltip>
                </div>
            )
        },
        {
            title: '变更后',
            dataIndex: 'toOrgName',
            width: 300,
            render: (text, record) => {
                const orgData = mapTreeData(
                    filterTreeData(departmentOrganizationTree, item => item.organizationCode !== record.fromOrgCode),
                    item => ({
                        ...item,
                        id: item.organizationCode,
                        key: item.organizationCode,
                        value: item.organizationCode,
                        title: item.auditStatus !== 2 ? `${item.organizationName} (审批中)` : item.organizationName,
                        selectable: !item.children
                    })
                );
                return (
                    <div>
                        <TreeSelect
                            value={record.toOrgCode}
                            onChange={val => handleChangeEmployeeOrganization(record.employeeCode, val)}
                            treeData={orgData}
                            placeholder="请选择组织机构"
                            showSearch
                            treeNodeFilterProp="title"
                            treeDefaultExpandedKeys={getTreeNodePath(orgData, 'organizationCode', record.toOrgCode).map(
                                item => item.organizationCode
                            )}
                            style={{ width: 300 }}
                            dropdownStyle={{ maxHeight: 370, overflowY: 'visible' }}
                            getPopupContainer={trigger => trigger.parentNode}
                        />
                        {/* &nbsp;
                        <Tooltip title={record.toFullOrgPathName} placement="top">
                            <Icon className="autoVisibleIcon" type="exclamation-circle" />
                        </Tooltip> */}
                    </div>
                );
            }
        },
        {
            title: '操作',
            dataIndex: 'dimensionTypeName',
            width: 120,
            align: 'center',
            render: (text, record) => (
                <Tooltip placement="top" title="取消变更">
                    <Icon.Button
                        dark
                        danger
                        icon="iconlistfunction_delete_icon_default"
                        style={{ fontSize: 22 }}
                        onClick={() => handleDeleteEmployeeData(record.employeeCode)}
                    />
                </Tooltip>
            )
        }
    ];

    useImperativeHandle(ref, () => ({}));

    const reverseValue = [...value].reverse();
    return (
        <div className={styles.employeeManage}>
            <Spin spinning={employeeAndOrgLoading}>
                <EmployeeTransfer
                    treeData={departmentOrganizationTree}
                    allLeaves={allLeaves}
                    onChange={handleAddEmployeeData}
                    basePath={baseOrganizationPath}
                />
                {value.length > 0 ? (
                    <>
                        <div style={{ margin: '32px 0 16px', lineHeight: 1 }}>变更结果</div>
                        <Table
                            style={{ marginTop: '12px' }}
                            className={styles.employeeSelectedList}
                            dataSource={reverseValue}
                            columns={columns}
                            rowKey="employeeCode"
                            pagination={false}
                        />
                    </>
                ) : null}
            </Spin>
        </div>
    );
});

EmployeeManage.displayName = 'EmployeeManage';

export default EmployeeManage;
